package com.fs.uc.base.repo;

import com.fs.uc.base.domain.AdditionalRole;
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import io.smallrye.common.constraint.Assert;

import javax.enterprise.context.ApplicationScoped;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 崔超
 * 2021/12/6
 */
@ApplicationScoped
public class AdditionalRoleRepository implements PanacheRepository<AdditionalRole> {
    static final String ORG_ID_FIELD = "orgId";
    static final String USER_ID_FIELD = "userId";
    static final String ROLE_ID_FIELD = "roleId";

    public List<Long> findRoleIds(Long orgId, Long userId) {
        String query = String.format("%s=?1 and %s=?2", ORG_ID_FIELD, USER_ID_FIELD);
        return stream(query, orgId, userId).map(ar -> ar.roleId).collect(Collectors.toList());
    }

    public void removeByOrgUser(Long orgId, Long userId) {
        String query = String.format("%s=?1 and %s=?2", ORG_ID_FIELD, USER_ID_FIELD);
        delete(query, orgId, userId);
    }

    public void removeByOrgAndRole(Long orgId, Long roleId) {
        String query = String.format("%s=?1 and %s=?2", ORG_ID_FIELD, ROLE_ID_FIELD);
        delete(query, orgId, roleId);
    }

    public void save(AdditionalRole ar){
        Assert.assertNotNull(ar.orgId);
        Assert.assertNotNull(ar.userId);
        Assert.assertNotNull(ar.roleId);
        String query = String.format("%s=?1 and %s=?2 and %s=?3",ORG_ID_FIELD,USER_ID_FIELD,ROLE_ID_FIELD);
        Optional<AdditionalRole> additionalRole = find(query, ar.orgId, ar.userId, ar.roleId).firstResultOptional();
        if (additionalRole.isPresent()) {
            return;
        }
        persist(ar);
    }
}
